import React, { useState, useRef, useEffect, useCallback } from 'react';
import { udp } from "@cscec/udp-mobile-ui";
import './index.less';
import { 
  ContentOutline, 
  MessageFill, 
  PhoneFill, 
  UserAddOutline, 
  UserCircleOutline,
  UserOutline,
} from 'antd-mobile-icons';
import { Button, Form, Input, Image, Toast, Picker } from 'antd-mobile';
import { registerForParent, uploadImage } from './service';
import { message } from 'antd';

// 类型定义
interface FormData {
  userName: string;
  phone: string;
  verifyCode: string;
  studentName: string;
  grade: string;
  type: 0 | 1 | 2;
  img: string | null; // 修改为 string 类型，存储返回的 URL
}

interface Errors {
  userName: boolean;
  phone: boolean;
  verifyCode: boolean;
  studentName: boolean;
  grade: boolean;
  img: boolean;
}

interface GradeOption {
  label: string;
  value: string;
}

// 年级选项配置
const GRADE_OPTIONS: GradeOption[] = [
  { label: '小学一年级', value: '1' },
  { label: '小学二年级', value: '2' },
  { label: '小学三年级', value: '3' },
  { label: '小学四年级', value: '4' },
  { label: '小学五年级', value: '5' },
  { label: '小学六年级', value: '6' },
  { label: '初中一年级', value: '7' },
  { label: '初中二年级', value: '8' },
  { label: '初中三年级', value: '9' }
];

const PURPOSE_OPTIONS = [
  { label: '正式学员（已报名课程）', value: 0 },
  { label: '集赞兑换免费使用', value: 1 },
  { label: '课程咨询，想了解更多', value: 2 }
];

const ParentRegister: React.FC = () => {
  // 表单数据
  const [formData, setFormData] = useState<FormData>({
    userName: '',
    phone: '',
    verifyCode: '',
    studentName: '',
    grade: '',
    type:0,
    img: null, // 现在存储的是 URL 字符串
  });

  // UI 状态
  const [errors, setErrors] = useState<Errors>({
    userName: false,
    phone: false,
    verifyCode: false,
    studentName: false,
    grade: false,
    img: false,
  });

  const [codeCountdown, setCodeCountdown] = useState(0);
  const [isUploading, setIsUploading] = useState(false); // 新增上传状态
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [gradeVisible, setGradeVisible] = useState(false);

  const fileInputRef = useRef<HTMLInputElement>(null);
  const codeTimerRef = useRef<NodeJS.Timeout>();

  // 清理定时器
  useEffect(() => {
    return () => {
      if (codeTimerRef.current) {
        clearInterval(codeTimerRef.current);
      }
    };
  }, []);

  // 通用的输入处理函数
  const handleInputChange = useCallback((field: keyof FormData) => 
    (value: string) => {
      setFormData(prev => ({ ...prev, [field]: value }));
      
      // 清除对应字段的错误状态
      if (errors[field as keyof Errors]) {
        setErrors(prev => ({ ...prev, [field]: false }));
      }
    }, [errors]);

  // 处理单选按钮变化
  const handleRadioChange = useCallback((value:any) => {
    setFormData(prev => ({ ...prev, type: value }));
  }, []);

  // 处理年级选择
  const handleGradeChange = useCallback((value: string[]) => {
    if (value[0]) {
      setFormData(prev => ({ ...prev, grade: value[0] }));
      setErrors(prev => ({ ...prev, grade: false }));
    }
    setGradeVisible(false);
  }, []);

  // 文件上传处理
  const handleFileChange = useCallback(async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    // 验证文件类型和大小
    const validTypes = ['image/jpeg', 'image/jpg', 'image/png'];
    const maxSize = 5 * 1024 * 1024; // 5MB

    if (!validTypes.includes(file.type)) {
      Toast.show('请上传 JPG 或 PNG 格式的图片');
      return;
    }

    if (file.size > maxSize) {
      Toast.show('图片大小不能超过 5MB');
      return;
    }

    setIsUploading(true);
    
    try {
      // 调用后端接口上传图片
      const response = await uploadImage(file, 4);
      
      // 假设后端返回的数据结构为 { data: { url: '图片URL' } }
      // 根据实际后端返回结构调整
      const imageUrl = response.data?.url;
      
      if (imageUrl) {
        setFormData(prev => ({ ...prev, img: imageUrl }));
        setErrors(prev => ({ ...prev, img: false }));
        Toast.show('图片上传成功');
      } else {
        throw new Error('上传失败，未返回图片URL');
      }
    } catch (error) {
      console.error('图片上传失败:', error);
      Toast.show('图片上传失败，请重试');
      // 清空文件输入
      if (fileInputRef.current) {
        fileInputRef.current.value = '';
      }
    } finally {
      setIsUploading(false);
    }
  }, []);

  // 触发文件选择
  const triggerFileInput = useCallback(() => {
    if (!isUploading) {
      fileInputRef.current?.click();
    }
  }, [isUploading]);

  // 获取验证码
  const handleGetCode = useCallback(() => {
    const phone = formData.phone.trim();
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      setErrors(prev => ({ ...prev, phone: true }));
      Toast.show('请填写正确的手机号码');
      return;
    }

    // 开始倒计时
    setCodeCountdown(60);
    codeTimerRef.current = setInterval(() => {
      setCodeCountdown(prev => {
        if (prev <= 1) {
          clearInterval(codeTimerRef.current);
          return 0;
        }
        return prev - 1;
      });
    }, 1000);

    // 模拟发送验证码
    Toast.show('验证码已发送，请注意查收~');
  }, [formData.phone]);

  // 验证表单
  const validateForm = useCallback((): boolean => {
    const newErrors: Errors = {
      userName: !formData.userName.trim(),
      phone: !/^1[3-9]\d{9}$/.test(formData.phone.trim()),
      verifyCode: !formData.verifyCode.trim() || formData.verifyCode.length !== 6,
      studentName: !formData.studentName.trim(),
      grade: !formData.grade,
      img: formData.type == 1 && !formData.img, // 现在检查的是 URL 字符串
    };

    setErrors(newErrors);
    return !Object.values(newErrors).some(error => error);
  }, [formData]);

  // 提交表单
  const handleSubmit = useCallback(async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!validateForm()) {
      Toast.show('请完善表单信息');
      return;
    }

    setIsSubmitting(true);
    
    try {
      // 这里可以添加实际的提交逻辑
      console.log('表单提交数据:', formData);
      const res:any = await registerForParent(formData)
      console.log(res)
      if(res.code==200){
          Toast.show('注册申请提交成功！');
          udp.close()
      }else{
        message.error(res.msg)
      }
    } catch (error) {
      Toast.show('提交失败，请重试');
    } finally {
      setIsSubmitting(false);
    }
  }, [formData, validateForm]);

  // 清除图片
  const clearImage = useCallback(() => {
    setFormData(prev => ({ ...prev, img: null }));
    if (fileInputRef.current) {
      fileInputRef.current.value = '';
    }
  }, []);

  // 获取当前选中的年级标签
  const selectedGradeLabel = GRADE_OPTIONS.find(opt => opt.value === formData.grade)?.label || '请选择';

  return (
    <div className="parent-register">
      {/* 装饰元素 */}
      <div className="decoration-bubble bubble-1"></div>
      <div className="decoration-bubble bubble-2"></div>
      <div className="decoration-bubble bubble-3"></div>

      {/* 主内容 */}
      <div className="register-container">
        {/* 品牌区域 */}
        <div className="brand-section">
          <div className="logo float">
            <UserAddOutline className="logo-icon" />
          </div>
          <h1 className="brand-title">家长注册</h1>
          <p className="brand-subtitle">填写信息，开启英语学习之旅</p>
        </div>

        {/* 注册表单区域 */}
        <div className="form-container">
          <p className="form-notice">
            <span className="required-mark">*</span>
            <span>表示为必填字段</span>
          </p>

          <form onSubmit={handleSubmit} className="register-form">
            {/* 家长姓名 */}
            <div className="form-field">
              <label htmlFor="parent-name" className="field-label">
                家长姓名 <span className="required-mark">*</span>
              </label>
              <div className="input-wrapper">
                <UserOutline className="input-icon" />
                <Input
                  id="parent-name"
                  value={formData.userName}
                  placeholder="请输入您的姓名"
                  className={`register-input ${errors.userName ? 'error' : ''}`}
                  onChange={handleInputChange('userName')}
                  onFocus={() => setErrors(prev => ({ ...prev, userName: false }))}
                />
              </div>
              {errors.userName && (
                <p className="error-text show">
                  <span>请填写正确的姓名</span>
                </p>
              )}
            </div>

            {/* 家长手机号 + 验证码 */}
            <div className="form-field phone-verify-field">
              <div className="phone-field">
                <label htmlFor="parent-phone" className="field-label">
                  家长手机号 <span className="required-mark">*</span>
                </label>
                <div className="input-wrapper">
                  <PhoneFill className="input-icon" />
                  <Input
                    type="tel"
                    id="parent-phone"
                    value={formData.phone}
                    maxLength={11}
                    className={`register-input ${errors.phone ? 'error' : ''}`}
                    placeholder="请填写手机号"
                    onChange={handleInputChange('phone')}
                    onFocus={() => setErrors(prev => ({ ...prev, phone: false }))}
                  />
                </div>
                {errors.phone && (
                  <p className="error-text show">
                    <span>请填写正确的手机号</span>
                  </p>
                )}
              </div>
              <div className="verify-btn-wrapper">
                <button
                  type="button"
                  className={`verify-btn ${codeCountdown > 0 ? 'disabled' : ''}`}
                  onClick={handleGetCode}
                  disabled={codeCountdown > 0}
                >
                  {codeCountdown > 0 ? `${codeCountdown}s后重新获取` : '获取验证码'}
                </button>
              </div>
            </div>

            {/* 短信验证码 */}
            <div className="form-field">
              <label htmlFor="verify-code" className="field-label">
                短信验证码 <span className="required-mark">*</span>
              </label>
              <div className="input-wrapper">
                <MessageFill className="input-icon" />
                <Input
                  type="text"
                  id="verify-code"
                  value={formData.verifyCode}
                  maxLength={6}
                  className={`register-input ${errors.verifyCode ? 'error' : ''}`}
                  placeholder="请输入6位验证码"
                  onChange={handleInputChange('verifyCode')}
                  onFocus={() => setErrors(prev => ({ ...prev, verifyCode: false }))}
                />
              </div>
              {errors.verifyCode && (
                <p className="error-text show">
                  <span>请填写正确的验证码</span>
                </p>
              )}
            </div>

            {/* 学生姓名 */}
            <div className="form-field">
              <label htmlFor="studentName" className="field-label">
                学生姓名 <span className="required-mark">*</span>
              </label>
              <div className="input-wrapper">
                <UserCircleOutline className="input-icon" />
                <Input
                  type="text"
                  id="studentName"
                  value={formData.studentName}
                  className={`register-input ${errors.studentName ? 'error' : ''}`}
                  placeholder="请填写学生姓名"
                  onChange={handleInputChange('studentName')}
                  onFocus={() => setErrors(prev => ({ ...prev, studentName: false }))}
                />
              </div>
              {errors.studentName && (
                <p className="error-text show">
                  <span>请填写学生姓名</span>
                </p>
              )}
            </div>

            {/* 学生年级 */}
            <div className="form-field">
              <label className="field-label">
                学生年级 <span className="required-mark">*</span>
              </label>
              <div className="input-wrapper">
                <ContentOutline className="input-icon" />
                <div 
                  className={`grade-selector ${errors.grade ? 'error' : ''}`}
                  onClick={() => setGradeVisible(true)}
                  style={{
                    backgroundColor:'#fff',
                    fontSize:'16px',
                    border:'1px solid #d9d9d9' ,
                    height:'42px',
                    paddingLeft:'40px',
                    paddingRight:'40px',
                    borderRadius:'16px',
                    lineHeight:'39px',
                  }}
                >
                  {selectedGradeLabel}
                </div>
                <Picker
                  columns={[GRADE_OPTIONS]}
                  visible={gradeVisible}
                  onClose={() => setGradeVisible(false)}
                  onConfirm={handleGradeChange}
                />
              </div>
              {errors.grade && (
                <p className="error-text show">
                  <span>请选择学生年级</span>
                </p>
              )}
            </div>

            {/* 注册目的 */}
            <div className="form-field">
              <label className="field-label">
                注册目的 <span className="required-mark">*</span>
              </label>
              <div className="radio-group">
                {PURPOSE_OPTIONS.map(option => (
                  <label key={option.value} className="radio-option">
                    <input
                      type="radio"
                      name="register-type"
                      value={option.value}
                      checked={formData.type == option.value}
                      onChange={(e) => handleRadioChange(e.target.value)}
                    />
                    <span>{option.label}</span>
                  </label>
                ))}
              </div>
            </div>

            {/* 集赞截图 */}
            {formData.type == 1 && (
              <div className="form-field">
                <label className="field-label">
                  集赞截图 <span className="required-mark">*</span>
                </label>
                <div
                  className="upload-box"
                  onClick={triggerFileInput}
                  style={{ cursor: isUploading ? 'not-allowed' : 'pointer' }}
                >
                  <input
                    type="file"
                    ref={fileInputRef}
                    accept="image/jpeg,image/jpg,image/png"
                    className="file-input"
                    onChange={handleFileChange}
                    style={{ display: 'none' }}
                    disabled={isUploading}
                  />
                  {isUploading ? (
                    <div className="uploading-state">
                      <i className="fa fa-spinner fa-spin"></i>
                      <p className="upload-text">图片上传中...</p>
                    </div>
                  ) : (
                    <>
                      <i className="fa fa-upload upload-icon"></i>
                      <p className="upload-text">
                        点击上传集赞截图<br />支持JPG、PNG格式，最大5MB
                      </p>
                    </>
                  )}
                </div>
                {errors.img && (
                  <p className="error-text show">
                    <span>请上传集赞截图</span>
                  </p>
                )}
                {formData.img && (
                  <div className="img-preview">
                    <Image src={formData.img} alt="集赞截图"  />
                    <button
                      type="button"
                      className="preview-remove"
                      onClick={clearImage}
                      disabled={isUploading}
                    >
                      ×
                    </button>
                  </div>
                )}
              </div>
            )}

            {/* 提交按钮 */}
            <button
              type="submit"
              className="submit-btn"
              disabled={isSubmitting || isUploading}
            >
              {isSubmitting ? (
                <>
                  <i className="fa fa-spinner fa-spin"></i>
                  <span>提交中...</span>
                </>
              ) : (
                <span>提交注册申请</span>
              )}
            </button>

            {/* 返回登录 */}
            <div className="back-login" onClick={() => { udp.open("/EconomicIndex") }}>
              返回登录页
            </div>
          </form>
        </div>

        {/* 底部提示 */}
        <div className="footer-notice">
          <p>
            <i className="fa fa-info-circle"></i>
            提交后工作人员将尽快审核，结果将通过短信通知您~
          </p>
        </div>
      </div>
    </div>
  );
};

export default ParentRegister;